//
//  GWLiveApiManager.m
//  OMCUVideo
//
//  Created by dvt04 on 2017/6/21.
//  Copyright © 2017年 sumavision. All rights reserved.
//

#import "GWLiveApiManager.h"

@implementation GWLiveApiManager

{
    NSArray *_upnpDevices; //BasicUPnPDevice*
    
}

+ (GWLiveApiManager *)sharedManager
{
    static GWLiveApiManager *_liveApiManager = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _liveApiManager = [[GWLiveApiManager alloc]init];
    });
    
    return _liveApiManager;
    
}

-(instancetype)init
{
    self = [super init];
    
    if (self) {
        UPnPDB* db = [[UPnPManager GetInstance] DB];
        
        _upnpDevices = [db rootDevices]; //BasicUPnPDevice
        
        [db addObserver:(id <UPnPDBObserver>)self];
        
        [[[UPnPManager GetInstance] SSDP] setUserAgentProduct:@"upnpxdemo/1.0" andOS:@"OSX"];
        
        [[[UPnPManager GetInstance] SSDP] searchSSDP];

    }
    return self;
}



- (NSURLSessionDataTask *)request_ChannelList_Success:(GWSuccessBlock)ApiSuccessBlock failure:(GWFailureBlock)ApiFailureBlock
{
    
    NSURLSessionDataTask *task = [[GWBaseApiManager alloc]requestData_WithPost_ServerUrl:GWA7ServerUrl apiPath:@"GetChannels" withParams:nil withBodyParams:nil success:^(NSURLSessionDataTask *task, id data) {
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    return task;
}




#pragma mark - BasicUPnPServiceObserver

- (void)basicUPnPService:(BasicUPnPService *)service receivedEvents:(NSDictionary *)events
{
    NSLog(@"BasicUPnPServiceObserver did got events : %@ service : %@", events, service);
    
}


#pragma mark - UPnPDBObserver
-(void)UPnPDBWillUpdate:(UPnPDB*)sender{
    NSLog(@"UPnPDBWillUpdate %lu", (unsigned long)[_upnpDevices count]);
}

- (void)UPnPDBUpdated:(UPnPDB*)sender
{
    
    for (BasicUPnPDevice *device in _upnpDevices) {
        
        NSLog(@"[device urn] is %@",[device urn]);
        NSLog(@"[device modelName] is %@",[device modelName]);
        NSLog(@"[device manufacturer] is %@",[device manufacturer]);
        
        //找到事件设备
        if([[device urn] isEqualToString:@"urn:gcable:device:EventDevice:1"] && [[device modelName] rangeOfString:@"GCABLE_EVENT"].location != NSNotFound && [[device manufacturer] rangeOfString:@"GCABLE"].location != NSNotFound) {
            
            if ([device isKindOfClass:[BasicUPnPDevice class]]) {
                BasicUPnPService *service = [device getServiceForType:@"urn:gcable:service:EventService:1"];
                
                // media service event
                if ([service isObserver:(BasicUPnPServiceObserver*)self] == NO) {
                    [service addObserver:(BasicUPnPServiceObserver*)self];
                }
            }
        }
    }
    
//    NSLog(@"UPnPDBUpdated %lu", (unsigned long)[_upnpDevices count]);
//    if (foundedUpnpServer == NO) {
//        for (BasicUPnPDevice *device in _upnpDevices) {
//            
//            NSLog(@"[device urn] is %@",[device urn]);
//            NSLog(@"[device modelName] is %@",[device modelName]);
//            NSLog(@"[device manufacturer] is %@",[device manufacturer]);
//            
//            
//            //找到直播设备
//            
//            if([[device urn] isEqualToString:@"urn:schemas-upnp-org:device:MediaServer:1"] && [[device modelName] rangeOfString:@"GCABLE_LIVE"].location != NSNotFound && [[device manufacturer] rangeOfString:@"GCABLE"].location != NSNotFound) {
//                
//                MediaServer1Device *server = (MediaServer1Device*)device;
//                BasicUPnPService *service = [server contentDirectoryService];
//                
//                // media service event
//                if ([service isObserver:(BasicUPnPServiceObserver*)self] == NO) {
//                    [service addObserver:(BasicUPnPServiceObserver*)self];
//                }
//                
//                //Allocate NMSutableString's to read the results
//                NSMutableString *outResult = [[NSMutableString alloc] init];
//                NSMutableString *outNumberReturned = [[NSMutableString alloc] init];
//                NSMutableString *outTotalMatches = [[NSMutableString alloc] init];
//                NSMutableString *outUpdateID = [[NSMutableString alloc] init];
//                
//                BOOL isNeepLoop = YES;
//                while (isNeepLoop) {
//                    NSInteger ret = [[server contentDirectory] BrowseWithObjectID:@"GCABLE_LIVE_GROUP" BrowseFlag:@"BrowseDirectChildren" Filter:@"*" StartingIndex:@"0" RequestedCount:@"0" SortCriteria:@"+dc:title" OutResult:outResult OutNumberReturned:outNumberReturned OutTotalMatches:outTotalMatches OutUpdateID:outUpdateID];
//                    if (ret == 0) {
//                        isNeepLoop = NO;
//                    }
//                }
//                
//                while (1) {
//                    if (outResult.length >1 && ([[outResult substringToIndex:1] isEqual:@"\r"] || [[outResult substringToIndex:1] isEqual:@"\n"])) {
//                        [outResult deleteCharactersInRange:NSMakeRange(0, 1)];
//                    } else {
//                        break;
//                    }
//                }
//                
//                NSLog(@"GCABLE_LIVE_GROUP outResult is %@",outResult);
//                
//                NSMutableArray *arrmPlayList = [NSMutableArray arrayWithCapacity:0];
//                NSData *didl = [outResult dataUsingEncoding:NSUTF8StringEncoding];
//                MediaServerBasicObjectParser *parser = [[MediaServerBasicObjectParser alloc] initWithMediaObjectArray:arrmPlayList itemsOnly:NO];
//                [parser parseFromData:didl];
//                
//       
//                
//                for (MediaServer1BasicObject *item in arrmPlayList) {
//                    if ([item isContainer]) {
//                        MediaServer1ContainerObject *conntainer = (MediaServer1ContainerObject *)item;
//                        [dictLiveCategory setObject:[conntainer title] forKey:[conntainer objectID]];
//                        
//                        TSLiveCategory *liveCategory = [[TSLiveCategory alloc] init];
//                        liveCategory.categoryID = [conntainer objectID];
//                        liveCategory.categoryName = [conntainer title];
//                        liveCategory.imageUrl = @"";
//                        [arraytLiveCategary addObject:liveCategory];
//                        
//                    }
//                }
//                
//                for (MediaServer1BasicObject *item in arrmPlayList) {
//                    if ([item isContainer]) {
//                        
//                        MediaServer1ContainerObject *conntainer = (MediaServer1ContainerObject *)item;
//                        
//                        //Allocate NMSutableString's to read the results
//                        NSMutableString *outResult = [[NSMutableString alloc] init];
//                        NSMutableString *outNumberReturned = [[NSMutableString alloc] init];
//                        NSMutableString *outTotalMatches = [[NSMutableString alloc] init];
//                        NSMutableString *outUpdateID = [[NSMutableString alloc] init];
//                        
//                        
//                        [[server contentDirectory] BrowseWithObjectID:[conntainer objectID] BrowseFlag:@"BrowseDirectChildren" Filter:@"*" StartingIndex:@"0" RequestedCount:@"0" SortCriteria:@"+dc:title" OutResult:outResult OutNumberReturned:outNumberReturned OutTotalMatches:outTotalMatches OutUpdateID:outUpdateID];
//                        
//                        //                        BOOL isNeepLoop = YES;
//                        //                        while (isNeepLoop) {
//                        //                            NSInteger ret = [[server contentDirectory] BrowseWithObjectID:[conntainer objectID] BrowseFlag:@"BrowseDirectChildren" Filter:@"*" StartingIndex:@"0" RequestedCount:@"0" SortCriteria:@"+dc:title" OutResult:outResult OutNumberReturned:outNumberReturned OutTotalMatches:outTotalMatches OutUpdateID:outUpdateID];
//                        //                            if (ret == 0) {
//                        //                                isNeepLoop = NO;
//                        //                            }
//                        //                        }
//                        
//                        
//                        while (1) {
//                            if (outResult.length >1 && ([[outResult substringToIndex:1] isEqual:@"\r"] || [[outResult substringToIndex:1] isEqual:@"\n"])) {
//                                [outResult deleteCharactersInRange:NSMakeRange(0, 1)];
//                            } else {
//                                break;
//                            }
//                        }
//                        
//                        NSLog(@"GCABLE_CHANNEL_CATEGORY outResult is %@",outResult);
//                        
//                        NSMutableArray *arrmPlayList = [NSMutableArray arrayWithCapacity:0];
//                        NSData *didl = [outResult dataUsingEncoding:NSUTF8StringEncoding];
//                        MediaServerBasicObjectParser *parser = [[MediaServerBasicObjectParser alloc] initWithMediaObjectArray:arrmPlayList itemsOnly:NO];
//                        [parser parseFromData:didl];
//                        
//                        NSXMLParser *parse = [[NSXMLParser alloc]initWithData:didl];
//                        parse.categoryId = [conntainer objectID];
//                        [parse setDelegate:(id<NSXMLParserDelegate>)self];
//                        [parse parse];
//                        
//                    }
//                }
//                break;
//            }
//        }
//    }
}



@end
